<?php
/**
 * 微信公众号用户
 */
namespace app\wechat\admin;

use app\system\admin\Admin;
use app\common\model\WechatUser as WechatUserModel;
use app\common\service\SystemUser as SystemUserService;
use think\Console;

class User extends Admin
{
    protected $hisiModel = 'WechatUser';//模型名称[通用添加、修改专用]
    protected $hisiValidate = '';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();

    	$this->assign('systemUserKV', (new SystemUserService())->getKVList(1));
    }

    public function index()
    {
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$keyword    = $this->request->param('keyword/s');

    		$where    = [];
    		if ($keyword) {
    			$where[] = ['nickname|remark', 'like', "%{$keyword}%"];
    		}
            $systemUser=$systemUserKV = getSystemUserKV(null);
    		$order = 'id desc';
    		$data['data'] = WechatUserModel::where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $key=>&$uinfo){
    		    $uinfo['nick']=isset($systemUser[$uinfo['admin_id']]) ? $systemUser[$uinfo['admin_id']] : '';
            }
    		$data['count'] = WechatUserModel::where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * [通用方法]编辑页面展示和保存
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function edit()
    {
    	if ($this->request->isPost()) {// 数据验证
    		$postData = $this->request->post();
    		if ($this->hisiValidate) {
    			if (strpos($this->hisiValidate, '\\') === false ) {
    				if (defined('IS_PLUGINS')) {
    					$this->hisiValidate = 'plugins\\'.$this->request->param('_p').'\\validate\\'.$this->hisiValidate;
    				} else {
    					$this->hisiValidate = 'app\\'.$this->request->module().'\\validate\\'.$this->hisiValidate;
    				}
    			}

    			if ($this->hisiEditScene) {
    				$this->hisiValidate = $this->hisiValidate.'.'.$this->hisiEditScene;
    			}

    			$result = $this->validate($postData, $this->hisiValidate);
    			if ($result !== true) {
    				return $this->error($result);
    			}
    		}
    	}

    	$where = [];
    	$model = $this->model();
    	$pk = $model->getPk();
    	$id = $this->request->param($pk);

    	$where[]= [$pk, '=', $id];
    	$where  = $this->getRightWhere($where);

    	if ($this->request->isPost()) {

    		if ($model->save($postData, $where) === false) {
    			return $this->error($model->getError());
    		}

    		$formData = $model->where($where)->find()->toArray();
    		db('system_user')->where('id', $postData['admin_id'])->update(['avatar' => $formData['avatar']]);

    		return $this->success('保存成功', '');
    	}

    	$formData = $model->where($where)->find();

    	if (!$formData) {
    		return $this->error('数据不存在或没有权限');
    	}

    	$this->assign('formData', $formData);
    	$template = $this->request->param('template', 'form');

    	return $this->fetch($template);
    }

    /**
     * 同步微信公众号用户
     *
     * @author KING
     * @date 2020年7月6日
     *
     * @return \think\response\Json
     */
    public function sync() {
    	$output = Console::call('cronSyncWechatUser', ['--print=0']);
    	$res = json_decode($output->fetch(), true);
    	if ($res['code'] == 1) {
	    	$data['code'] = 1;
	    	$data['msg'] = '同步微信公众号用户成功';
    	} else {
    		$data['code'] = 0;
    		$data['msg'] = '同步微信公众号用户失败';
    	}
    	return json($data);
    }
}